<?php
include("config.php");

mysql_connect($host,$username,$password);
mysql_select_db($database) or die( "Unable to select database");

$hg_id=mysql_real_escape_string($_POST['hg_id']);
$name=mysql_real_escape_string($_POST['name']);
$message=mysql_real_escape_string($_POST['message']);
$email=mysql_real_escape_string($_POST['email']);
$cell=mysql_real_escape_string($_POST['cell']);

$query="SELECT email,cell FROM Homegroup h WHERE h.hg_id= ".$hg_id;
$result=mysql_query($query);
$to_email=mysql_result($result,0,"email");
$to_sms=mysql_result($result,0,"cell");
if(substr($to_sms,0,1)!="0")
{
	$to_sms="0".$to_sms;
}

$contact_details="";
$contact_msg="";

if($email!="" && $cell!="")
{
	$contact_details="Their email address is ".$email." and their cell phone number is ".$cell;
}
else if($email!="")
{
	$contact_details="Their email address is ".$email;
}
else if($cell!="")
{
	$contact_details="Their cell phone number is ".$cell;
}

if($message!="")
{
	$contact_msg="The message they left was: \n\"".$message."\"";
	
}
   
	$sms_msg="Hi there, ".$name." is interested in your homegroup. Please contact them ASAP. ".$contact_details.". Thanks! Church-on-Main";
	$sms_msg=str_replace(" ","%20",$sms_msg);
    $email_message = "Hi there\n\n" .$name. " is interested in your homegroup. Please get in contact with them ASAP.\n ". $contact_details . ".\n" .$contact_msg. "\n\nThank you so much\nLove\nThe elders\nChurch on Main";
   
    mail($to_email,$subject,$email_message,$headers);
    mail("homegroups@churchonmain.org.za",$to_email,$email_message,$headers);
    
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, "http://www.mymessager.com/smsapi.php?user=".$smsUserName."&pass=".$smsPass."&action=sendsms&msg=".$sms_msg."&number=".$to_sms);
	
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$contents = curl_exec ($ch);
	curl_close ($ch);
	$date=date("F j, Y, g:i a");
	$contents=mysql_real_escape_string($contents);
	$insert="INSERT INTO log (hg_id,name,cell,email,message,to_email,to_sms,time,log_msg) VALUES ('$hg_id','$name','$cell','$email','$message','$to_email','$to_sms','$date','$contents')";
	mysql_query($insert);
$return_json = '{"success":"1"}';

echo $return_json;

?>